package com.hz.house.service.home;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hz.house.bean.entity.BuildingBannerAdvertisingBean;
import com.hz.house.bean.entity.OpenInfoBean;
import com.hz.house.bean.entity.SaleManBean;
import com.hz.house.bean.es.BuildingSearchDocumentBean;
import com.hz.house.bean.vo.*;
import com.hz.house.cache.HomePageCacheService;
import com.hz.house.cache.WxAcctkCacheService;
import com.hz.house.common.Constants;
import com.hz.house.common.DaysIntUtil;
import com.hz.house.common.HtmlToText;
import com.hz.house.common.ResultUtil;
import com.hz.house.dao.HomePageMapper;
import com.hz.house.enums.*;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.script.Script;
import org.elasticsearch.search.sort.NestedSortBuilder;
import org.elasticsearch.search.sort.ScriptSortBuilder.ScriptSortType;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;

/**
 * <p> 首页所有数据的业务处理都在这里了
 *
 * @author lfw
 */
@Service
@Slf4j
public class HomePageService {

    @Autowired
    private HomePageCacheService hpcs;

    @Autowired
    private HomePageMapper hpm;

    @Autowired
    private ElasticsearchTemplate esTemplate;

    public static String customerServiceUrl = "http://house-small-sellman/ms/customer";

    @Resource
    private RestTemplate ribonTemplate;

    @Resource
    private RestTemplate restTemplate;

    @Autowired
    private WxAcctkCacheService wxAcctkCacheService;

    private String zaobaoBackUrl = "https://housessmall-dev-index-img-1258778894.cos.ap-chengdu.myqcloud.com/icon/zb_bg.png";

    private String djUrl = "https://housessmall-dev-index-img-1258778894.cos.ap-chengdu.myqcloud.com/icon/dj.png";

    private String xwUrl = "https://housessmall-dev-index-img-1258778894.cos.ap-chengdu.myqcloud.com/icon/xw.png";

    private String yhUrl = "https://housessmall-dev-index-img-1258778894.cos.ap-chengdu.myqcloud.com/icon/yh.png";

    /**
     * <p>查询首页相关的所有广告
     * <p> 获取首页的顶部轮播广告，中部的轮播广告，搜索框内占位的楼盘名称广告，
     * <p> 搜索页内的热门楼盘名字广告，那5个列表内的轮播滚动广告
     *
     * @return
     */
    public Object getGuangGao(String type) {
        if (StringUtils.isEmpty(type))
            return ResultUtil.fail("广告类型错误");
        List<BuildingBannerAdvertisingBean> banners = hpcs.getBannerAdsCache(type);
        if (banners == null) {
            //走数据库
            banners = hpm.getBannerAds(type);
            hpcs.setBannerAdsCache(type, banners);
        }
        return ResultUtil.ok(banners);
    }

    public Object getGuangGaoV2_2(String type) {
        if (StringUtils.isEmpty(type))
            return ResultUtil.fail("广告类型错误");
        List<BuildingBannerAdvertisingBean> banners = hpcs.getBannerAdsCache(type);
        if (banners == null) {
            //走数据库
            banners = hpm.getBannerAds(type);
            List<BuildingBannerAdvertisingBean> ars = hpm.getArticleAds(type);
            dealAds(banners, ars);
            hpcs.setBannerAdsCache(type, banners);
        }
        return ResultUtil.ok(banners);
    }

    private void dealAds(List<BuildingBannerAdvertisingBean> banners, List<BuildingBannerAdvertisingBean> ars) {
        if (banners != null && banners.size() > 0)
            banners.forEach(b -> b.setMark(0));
        assert banners != null;
        assert ars != null;
        banners.addAll(ars);
    }


    /**
     * 获取筛选栏查询条件的格式化数据
     *
     * @return
     */
    public Object getSearchConditions() {

        Map<String, Object> m = new HashMap<>();

        //区域圈层
        List<SimpleCoditionBean> r1 = new ArrayList<>();
        for (SearchRegionEnum tp : SearchRegionEnum.getSearchRegionByCircle(1))
            r1.add(new SimpleCoditionBean(tp.getId(), tp.getName()));
        m.put("region_1", r1);
        List<SimpleCoditionBean> r2 = new ArrayList<>();
        for (SearchRegionEnum tp : SearchRegionEnum.getSearchRegionByCircle(2))
            r2.add(new SimpleCoditionBean(tp.getId(), tp.getName()));
        m.put("region_2", r2);
        List<SimpleCoditionBean> r3 = new ArrayList<>();
        for (SearchRegionEnum tp : SearchRegionEnum.getSearchRegionByCircle(3))
            r3.add(new SimpleCoditionBean(tp.getId(), tp.getName()));
        m.put("region_3", r3);
        List<SimpleCoditionBean> r4 = new ArrayList<>();
        for (SearchRegionEnum tp : SearchRegionEnum.getSearchRegionByCircle(4))
            r4.add(new SimpleCoditionBean(tp.getId(), tp.getName()));
        m.put("region_4", r4);
        //地铁线路
        List<SimpleCoditionBean> sub = new ArrayList<>();
        for (SearchSubwayEnum tp : SearchSubwayEnum.values())
            sub.add(new SimpleCoditionBean(tp.getId(), tp.getName()));
        m.put("subway", sub);
        //价格-总价
        List<SimpleCoditionBean> tpcss = new ArrayList<>();
        for (SearchTotalPriceConditionEnum tp : SearchTotalPriceConditionEnum.values())
            tpcss.add(new SimpleCoditionBean(tp.getId(), tp.getName()));
        m.put("price_total", tpcss);
        //价格-单价
        List<SimpleCoditionBean> ppcs = new ArrayList<>();
        for (SearchPerPriceConditionEnum tp : SearchPerPriceConditionEnum.values())
            ppcs.add(new SimpleCoditionBean(tp.getId(), tp.getName()));
        m.put("price_unit", ppcs);
        //面积
        List<SimpleCoditionBean> spcs = new ArrayList<>();
        for (SearchSpaceConditionEnum tp : SearchSpaceConditionEnum.values())
            spcs.add(new SimpleCoditionBean(tp.getId(), tp.getName()));
        m.put("space", spcs);
        //户型
        List<SimpleCoditionBean> hmcs = new ArrayList<>();
        for (SearchHouseModelConditionEnum tp : SearchHouseModelConditionEnum.values())
            hmcs.add(new SimpleCoditionBean(tp.getId(), tp.getName()));
        m.put("house_model", hmcs);
        //物业类型
        List<SimpleCoditionBean> ptcs = new ArrayList<>();
        for (SearchPropTypeConditionEnum tp : SearchPropTypeConditionEnum.values())
            ptcs.add(new SimpleCoditionBean(tp.getId(), tp.getName()));
        m.put("prop_type", ptcs);
        //装修情况
        List<SimpleCoditionBean> dcs = new ArrayList<>();
        for (SearchDecorateConditionEnum tp : SearchDecorateConditionEnum.values())
            dcs.add(new SimpleCoditionBean(tp.getId(), tp.getName()));
        m.put("decorate", dcs);
        //售卖状态
        List<SimpleCoditionBean> sts = new ArrayList<>();
        sts.add(new SimpleCoditionBean(100, "在售"));
        sts.add(new SimpleCoditionBean(1, "待售"));
        sts.add(new SimpleCoditionBean(2, "即将取证"));
        sts.add(new SimpleCoditionBean(10, "等待新推"));
        m.put("sell_status", sts);
        //排序
        List<SimpleCoditionBean> sort = new ArrayList<>();
        sort.add(new SimpleCoditionBean(1, "单价从低到高"));
        sort.add(new SimpleCoditionBean(2, "单价从高到低"));
        sort.add(new SimpleCoditionBean(3, "总价从低到高"));
        sort.add(new SimpleCoditionBean(4, "总价从高到低"));
        sort.add(new SimpleCoditionBean(5, "面积从小到大"));
        sort.add(new SimpleCoditionBean(6, "面积从大到小"));
        m.put("sort_index", sort);
        return ResultUtil.ok(m);
    }

    private long get5TypoeCounts(String type) {

        BuildingSearchConditionBean c = new BuildingSearchConditionBean();
        c.setBuildingType(type);
        BoolQueryBuilder metaQuery = QueryBuilders.boolQuery();
        handle5Type(c, metaQuery);
        Long x = esCountSearch(metaQuery);
        return x == null ? 0 : x;
    }

    private Long esCountSearch(QueryBuilder query) {
        SearchRequestBuilder req = esTemplate.getClient().prepareSearch(Constants.ES_BUILDING_INDEX_NAME)
                .setTypes(Constants.ES_TYPE_NAME_HOUSE);
        req.setQuery(query);
        req.setSize(0);
        //执行查询
        SearchResponse rep = req.execute().actionGet();
        return rep.getHits().getTotalHits();
    }


    //处理首页楼盘5大类分类
    private void handle5Type(BuildingSearchConditionBean condition, BoolQueryBuilder metaQuery) {
        //未选择类型，即为全部楼盘
        if (StringUtils.isEmpty(condition.getBuildingType())) {
            return;
        }
        //热门楼盘
        if (condition.getBuildingType().equals(Constants.HOME_PAGE_BUILDING_TYPE_RMLP)) {
            metaQuery.must(QueryBuilders.wildcardQuery("type", "*" + BuildingGroupEnum.hotBuild.getCode() + "*"));
        }
        //即将取证
        if (condition.getBuildingType().equals(Constants.HOME_PAGE_BUILDING_TYPE_JJQZ)) {
            metaQuery.must(QueryBuilders.wildcardQuery("type", "*" + BuildingGroupEnum.notCertification.getCode() + "*"));
        }
        //最新取证,比较特殊
        if (condition.getBuildingType().equals(Constants.HOME_PAGE_BUILDING_TYPE_ZXQZ)) {
            metaQuery.must(QueryBuilders.wildcardQuery("type", "*" + BuildingGroupEnum.newCertification.getCode() + "*"));
        }
        //最新摇号 满足678且5的时候当前时间大于开始公示时间
        if (condition.getBuildingType().equals(Constants.HOME_PAGE_BUILDING_TYPE_ZXYH)) {
            metaQuery.must(QueryBuilders.wildcardQuery("type", "*" + BuildingGroupEnum.newShakeNumber.getCode() + "*"));
        }
        //摇号剩余  剩余房源大于20套的任何状态下的楼盘
        if (condition.getBuildingType().equals(Constants.HOME_PAGE_BUILDING_TYPE_YHSY)) {
            metaQuery.must(QueryBuilders.wildcardQuery("type", "*" + BuildingGroupEnum.bestSellerBuild.getCode() + "*"));
        }
    }

    /**
     * <p> 获取每个类型的楼盘数量，找房的标签，金牌置业顾问
     * @return
     */
//	public Object getOtherDataV2_1() {
//		
//		Map<String,Object> m = new HashMap<>();
//		
//		//查询每个分类的楼盘数量并缓存到redis
//		Map<String,Long> typesCount = this.hpcs.getBuildingTypesCountsCache();
//		if(typesCount==null) {
//			typesCount = new HashMap<String, Long>();
//			typesCount.put("rmlp",get5TypoeCounts("rmlp"));
//			typesCount.put("jjqz",get5TypoeCounts("jjqz"));
//			typesCount.put("zxqz",get5TypoeCounts("zxqz"));
//			typesCount.put("zxyh",get5TypoeCounts("zxyh"));
//			typesCount.put("yhsy",get5TypoeCounts("yhsy"));
//			this.hpcs.setBuildingTypesCountsCache(typesCount);
//		}
//		m.put("types_counts", typesCount);
//		//2个金牌置业顾问
//		List<SaleManBean> golden = this.hpcs.getGoldenSaleManV2_1();
//		if(golden==null) {
//			//当前时间-30天
//			golden = this.hpm.getHomePageSaleManV2_1(DaysIntUtil.getDays(new Date())-30);
//			this.hpcs.setHomeSaleManCacheV2_1(golden);
//		}
//		m.put("sale_man", golden);
//		//首页找房标签
//		List<BuildingTag> tags = new ArrayList<>();
//		//第一排 户型标签
//		tags.add(new BuildingTag(SearchHouseModelConditionEnum.ONE_HOUSE.getId(),Constants.TAG_TYPE_HOUSE_MODEL,
//				SearchHouseModelConditionEnum.ONE_HOUSE.getName()));
//		tags.add(new BuildingTag(SearchHouseModelConditionEnum.TWO_HOUSE.getId(),Constants.TAG_TYPE_HOUSE_MODEL,
//				SearchHouseModelConditionEnum.TWO_HOUSE.getName()));
//		tags.add(new BuildingTag(SearchHouseModelConditionEnum.THREE_HOUSE.getId(),Constants.TAG_TYPE_HOUSE_MODEL,
//				SearchHouseModelConditionEnum.THREE_HOUSE.getName()));
//		tags.add(new BuildingTag(SearchHouseModelConditionEnum.FOUR_HOUSE.getId(),Constants.TAG_TYPE_HOUSE_MODEL,
//				SearchHouseModelConditionEnum.FOUR_HOUSE.getName()));
//		//第二排 总价标签
//		tags.add(new BuildingTag(SearchTagTotalPriceEnum.TOTAL_PRICE100.getId(),Constants.TAG_TYPE_TOTAL_PRICE,
//				SearchTagTotalPriceEnum.TOTAL_PRICE100.getName()));
//		tags.add(new BuildingTag(SearchTagTotalPriceEnum.TOTAL_PRICE100PLUS.getId(),Constants.TAG_TYPE_TOTAL_PRICE,
//				SearchTagTotalPriceEnum.TOTAL_PRICE100PLUS.getName()));
//		tags.add(new BuildingTag(SearchTagTotalPriceEnum.TOTAL_PRICE200PLUS.getId(),Constants.TAG_TYPE_TOTAL_PRICE,
//				SearchTagTotalPriceEnum.TOTAL_PRICE200PLUS.getName()));
//		tags.add(new BuildingTag(SearchTagTotalPriceEnum.TOTAL_PRICE300PLUS.getId(),Constants.TAG_TYPE_TOTAL_PRICE,
//				SearchTagTotalPriceEnum.TOTAL_PRICE300PLUS.getName()));
//		//第三排 自定义标签
//		tags.add(new BuildingTag(BuildingTagEnum.SCHOOL_HOUSE.getId(),Constants.TAG_TYPE_SYS,
//				BuildingTagEnum.SCHOOL_HOUSE.getName()));
//		tags.add(new BuildingTag(BuildingTagEnum.SUBWAY_ONE.getId(),Constants.TAG_TYPE_SYS,
//				BuildingTagEnum.SUBWAY_ONE.getName()));
//		tags.add(new BuildingTag(BuildingTagEnum.JIAN_DAO_CHA.getId(),Constants.TAG_TYPE_SYS,
//				BuildingTagEnum.JIAN_DAO_CHA.getName()));
//		tags.add(new BuildingTag(BuildingTagEnum.NOT_LIMIT_BUY.getId(),Constants.TAG_TYPE_SYS,
//				BuildingTagEnum.NOT_LIMIT_BUY.getName()));
//		m.put("home_tags", tags);
//		return ResultUtil.ok(m);
//	}

    /**
     * <p> 获取每个类型的楼盘数量，找房的标签，金牌置业顾问
     *
     * @return
     */
    public Object getOtherDataV2_2() {

        Map<String, Object> m = new HashMap<>();

        //查询每个分类的楼盘数量并缓存到redis
        Map<String, Long> typesCount = this.hpcs.getBuildingTypesCountsCache();
        if (typesCount == null) {
            typesCount = new HashMap<String, Long>();
            typesCount.put("rmlp", get5TypoeCounts("rmlp"));
            typesCount.put("jjqz", get5TypoeCounts("jjqz"));
            typesCount.put("zxqz", get5TypoeCounts("zxqz"));
            typesCount.put("zxyh", get5TypoeCounts("zxyh"));
            typesCount.put("yhsy", get5TypoeCounts("yhsy"));
            this.hpcs.setBuildingTypesCountsCache(typesCount);
        }
        m.put("types_counts", typesCount);
        //2个金牌置业顾问,活跃度和竞价我要上首页
        List<SaleManBean> golden = this.hpcs.getGoldenSaleManV2_2();
        if (golden == null) {
            //当前时间-30天
            golden = this.hpm.getHomePageSaleManV2_1(DaysIntUtil.getDays(new Date()) - 30);
            //查询是否有竞价上首页的
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SaleManBean s = hpm.getHomePageSaleManChuJia(sdf.format(new Date()), null, BidTypeEnum.HOME_PAGE_BID.getType());
            if (s != null) {
                //如果已经再首页展示了，竞价成功的不再展示
                if (golden.size() > 0) {
                    SaleManBean s1 = golden.get(0);//第一个不是出价的那个，就把第二个删了替换成出价成功者
                    if (s1.getCid().intValue() != s.getCid().intValue()) {
                        golden.set(1, s);
                    }
                }
            }
            this.hpcs.setHomeSaleManCacheV2_2(golden);
        }
        m.put("sale_man", golden);
        //首页找房标签
        List<BuildingTag> tags = new ArrayList<>();
        //第一排 户型标签
        tags.add(new BuildingTag(SearchHouseModelConditionEnum.ONE_HOUSE.getId(), Constants.TAG_TYPE_HOUSE_MODEL,
                SearchHouseModelConditionEnum.ONE_HOUSE.getName()));
        tags.add(new BuildingTag(SearchHouseModelConditionEnum.TWO_HOUSE.getId(), Constants.TAG_TYPE_HOUSE_MODEL,
                SearchHouseModelConditionEnum.TWO_HOUSE.getName()));
        tags.add(new BuildingTag(SearchHouseModelConditionEnum.THREE_HOUSE.getId(), Constants.TAG_TYPE_HOUSE_MODEL,
                SearchHouseModelConditionEnum.THREE_HOUSE.getName()));
        tags.add(new BuildingTag(SearchHouseModelConditionEnum.FOUR_HOUSE.getId(), Constants.TAG_TYPE_HOUSE_MODEL,
                SearchHouseModelConditionEnum.FOUR_HOUSE.getName()));
        //第二排 总价标签
        tags.add(new BuildingTag(SearchTagTotalPriceEnum.TOTAL_PRICE100.getId(), Constants.TAG_TYPE_TOTAL_PRICE,
                SearchTagTotalPriceEnum.TOTAL_PRICE100.getName()));
        tags.add(new BuildingTag(SearchTagTotalPriceEnum.TOTAL_PRICE100PLUS.getId(), Constants.TAG_TYPE_TOTAL_PRICE,
                SearchTagTotalPriceEnum.TOTAL_PRICE100PLUS.getName()));
        tags.add(new BuildingTag(SearchTagTotalPriceEnum.TOTAL_PRICE200PLUS.getId(), Constants.TAG_TYPE_TOTAL_PRICE,
                SearchTagTotalPriceEnum.TOTAL_PRICE200PLUS.getName()));
        tags.add(new BuildingTag(SearchTagTotalPriceEnum.TOTAL_PRICE300PLUS.getId(), Constants.TAG_TYPE_TOTAL_PRICE,
                SearchTagTotalPriceEnum.TOTAL_PRICE300PLUS.getName()));
        //第三排 自定义标签
        tags.add(new BuildingTag(BuildingTagEnum.SCHOOL_HOUSE.getId(), Constants.TAG_TYPE_SYS,
                BuildingTagEnum.SCHOOL_HOUSE.getName()));
        tags.add(new BuildingTag(BuildingTagEnum.SUBWAY_ONE.getId(), Constants.TAG_TYPE_SYS,
                BuildingTagEnum.SUBWAY_ONE.getName()));
        tags.add(new BuildingTag(BuildingTagEnum.JIAN_DAO_CHA.getId(), Constants.TAG_TYPE_SYS,
                BuildingTagEnum.JIAN_DAO_CHA.getName()));
        tags.add(new BuildingTag(BuildingTagEnum.NOT_LIMIT_BUY.getId(), Constants.TAG_TYPE_SYS,
                BuildingTagEnum.NOT_LIMIT_BUY.getName()));
        m.put("home_tags", tags);
        return ResultUtil.ok(m);
    }

    /**
     * <p> 获取每个类型的楼盘数量，找房的标签，金牌置业顾问
     *
     * @return
     */
    public Object getOtherDataV2_3() {

        Map<String, Object> m = new HashMap<>();

        //查询每个分类的楼盘数量并缓存到redis
        Map<String, Long> typesCount = this.hpcs.getBuildingTypesCountsCache();
        if (typesCount == null) {
            typesCount = new HashMap<String, Long>();
            typesCount.put("rmlp", get5TypoeCounts("rmlp"));
            typesCount.put("jjqz", get5TypoeCounts("jjqz"));
            typesCount.put("zxqz", get5TypoeCounts("zxqz"));
            typesCount.put("zxyh", get5TypoeCounts("zxyh"));
            typesCount.put("yhsy", get5TypoeCounts("yhsy"));
            this.hpcs.setBuildingTypesCountsCache(typesCount);
        }
        m.put("types_counts", typesCount);
        //2019-12-16日 两个金牌置业顾问变3个
        //3个金牌置业顾问,活跃度和竞价我要上首页
        List<SaleManBean> golden = this.hpcs.getGoldenSaleManV2_3();
        if (golden == null) {
            //当前时间-30天
            golden = this.hpm.getHomePageSaleManV2_1(DaysIntUtil.getDays(new Date()) - 30);
            //查询昨日之星第一个
            SaleManBean y = this.getYesterdayStar(null);
            if (y != null) {
                if (!isEq(golden, y.getCid())) {
                    golden.set(1, y);
                }
            }
            //查询是否有竞价上首页的
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SaleManBean s = hpm.getHomePageSaleManChuJia(sdf.format(new Date()), null, BidTypeEnum.HOME_PAGE_BID.getType());
            if (s != null) {
                if (!isEq(golden, s.getCid())) {
                    golden.set(2, s);
                }
            }
            this.hpcs.setHomeSaleManCacheV2_3(golden);
        }
        m.put("sale_man", golden);
        //首页找房标签
        List<BuildingTag> tags = new ArrayList<>();
        //第一排 户型标签
        tags.add(new BuildingTag(SearchHouseModelConditionEnum.ONE_HOUSE.getId(), Constants.TAG_TYPE_HOUSE_MODEL,
                SearchHouseModelConditionEnum.ONE_HOUSE.getName()));
        tags.add(new BuildingTag(SearchHouseModelConditionEnum.TWO_HOUSE.getId(), Constants.TAG_TYPE_HOUSE_MODEL,
                SearchHouseModelConditionEnum.TWO_HOUSE.getName()));
        tags.add(new BuildingTag(SearchHouseModelConditionEnum.THREE_HOUSE.getId(), Constants.TAG_TYPE_HOUSE_MODEL,
                SearchHouseModelConditionEnum.THREE_HOUSE.getName()));
        tags.add(new BuildingTag(SearchHouseModelConditionEnum.FOUR_HOUSE.getId(), Constants.TAG_TYPE_HOUSE_MODEL,
                SearchHouseModelConditionEnum.FOUR_HOUSE.getName()));
        //第二排 总价标签
        tags.add(new BuildingTag(SearchTagTotalPriceEnum.TOTAL_PRICE100.getId(), Constants.TAG_TYPE_TOTAL_PRICE,
                SearchTagTotalPriceEnum.TOTAL_PRICE100.getName()));
        tags.add(new BuildingTag(SearchTagTotalPriceEnum.TOTAL_PRICE100PLUS.getId(), Constants.TAG_TYPE_TOTAL_PRICE,
                SearchTagTotalPriceEnum.TOTAL_PRICE100PLUS.getName()));
        tags.add(new BuildingTag(SearchTagTotalPriceEnum.TOTAL_PRICE200PLUS.getId(), Constants.TAG_TYPE_TOTAL_PRICE,
                SearchTagTotalPriceEnum.TOTAL_PRICE200PLUS.getName()));
        tags.add(new BuildingTag(SearchTagTotalPriceEnum.TOTAL_PRICE300PLUS.getId(), Constants.TAG_TYPE_TOTAL_PRICE,
                SearchTagTotalPriceEnum.TOTAL_PRICE300PLUS.getName()));
        //第三排 自定义标签
        tags.add(new BuildingTag(BuildingTagEnum.SCHOOL_HOUSE.getId(), Constants.TAG_TYPE_SYS,
                BuildingTagEnum.SCHOOL_HOUSE.getName()));
        tags.add(new BuildingTag(BuildingTagEnum.SUBWAY_ONE.getId(), Constants.TAG_TYPE_SYS,
                BuildingTagEnum.SUBWAY_ONE.getName()));
        tags.add(new BuildingTag(BuildingTagEnum.JIAN_DAO_CHA.getId(), Constants.TAG_TYPE_SYS,
                BuildingTagEnum.JIAN_DAO_CHA.getName()));
        tags.add(new BuildingTag(BuildingTagEnum.NOT_LIMIT_BUY.getId(), Constants.TAG_TYPE_SYS,
                BuildingTagEnum.NOT_LIMIT_BUY.getName()));
        m.put("home_tags", tags);
        return ResultUtil.ok(m);
    }


    public boolean isEq(List<SaleManBean> golden, int customerId) {
        for (SaleManBean s : golden) {
            if (s.getCid().intValue() == customerId)
                return true;
        }
        return false;
    }

    public SaleManBean getYesterdayStar(Integer buildingId) {

        String url = customerServiceUrl + "/getYesterdayStar";
        if (!StringUtils.isEmpty(buildingId)){
            url = url + "?buildingId=" + buildingId;
        }
        String res = this.ribonTemplate.getForObject(url, String.class);
        System.out.println(res);
        JSONObject r = JSON.parseObject(res);
        if (r.getIntValue("code") != 200) {
            return null;
        }
        int customerId = r.getIntValue("data");
        if (customerId == 0) {
            return null;
        }
        //从数据库查询昨日之星的头像、名字、楼盘
        SaleManBean s = this.hpm.getSaleMan(customerId);
        return s;
    }

    /**
     * <p> 获取每个类型的楼盘数量，找房的标签，金牌置业顾问
     *
     * @return
     */
    public Object getOtherData() {

//		Map<String,Object> m = new HashMap<>();
//		
//		//查询每个分类的楼盘数量并缓存到redis
//		Map<String,Long> typesCount = this.hpcs.getBuildingTypesCountsCache();
//		if(typesCount==null) {
//			typesCount = new HashMap<String, Long>();
//			typesCount.put("rmlp",get5TypoeCounts("rmlp"));
//			typesCount.put("jjqz",get5TypoeCounts("jjqz"));
//			typesCount.put("zxqz",get5TypoeCounts("zxqz"));
//			typesCount.put("zxyh",get5TypoeCounts("zxyh"));
//			typesCount.put("yhsy",get5TypoeCounts("yhsy"));
//			this.hpcs.setBuildingTypesCountsCache(typesCount);
//		}
//		m.put("types_counts", typesCount);
//		//2个金牌置业顾问
//		List<SaleManBean> golden = this.hpcs.getGoldenSaleMan();
//		if(golden==null) {
//			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//			Date now = new Date();
//			String end = sdf.format(now);
//			Calendar cl = Calendar.getInstance();
//			cl.setTime(now);
//			cl.add(Calendar.DATE, -30);
//			String begin = sdf.format(cl.getTime());
//			golden = this.hpm.getHomePageSaleMan(begin, end);
//			this.hpcs.setHomeSaleManCache(golden);
//		}
//		m.put("sale_man", golden);
//		//首页找房标签
//		List<BuildingTag> tags = new ArrayList<>();
//		//第一排 户型标签
//		tags.add(new BuildingTag(SearchHouseModelConditionEnum.ONE_HOUSE.getId(),Constants.TAG_TYPE_HOUSE_MODEL,
//				SearchHouseModelConditionEnum.ONE_HOUSE.getName()));
//		tags.add(new BuildingTag(SearchHouseModelConditionEnum.TWO_HOUSE.getId(),Constants.TAG_TYPE_HOUSE_MODEL,
//				SearchHouseModelConditionEnum.TWO_HOUSE.getName()));
//		tags.add(new BuildingTag(SearchHouseModelConditionEnum.THREE_HOUSE.getId(),Constants.TAG_TYPE_HOUSE_MODEL,
//				SearchHouseModelConditionEnum.THREE_HOUSE.getName()));
//		tags.add(new BuildingTag(SearchHouseModelConditionEnum.FOUR_HOUSE.getId(),Constants.TAG_TYPE_HOUSE_MODEL,
//				SearchHouseModelConditionEnum.FOUR_HOUSE.getName()));
//		//第二排 总价标签
//		tags.add(new BuildingTag(SearchTagTotalPriceEnum.TOTAL_PRICE100.getId(),Constants.TAG_TYPE_TOTAL_PRICE,
//				SearchTagTotalPriceEnum.TOTAL_PRICE100.getName()));
//		tags.add(new BuildingTag(SearchTagTotalPriceEnum.TOTAL_PRICE100PLUS.getId(),Constants.TAG_TYPE_TOTAL_PRICE,
//				SearchTagTotalPriceEnum.TOTAL_PRICE100PLUS.getName()));
//		tags.add(new BuildingTag(SearchTagTotalPriceEnum.TOTAL_PRICE200PLUS.getId(),Constants.TAG_TYPE_TOTAL_PRICE,
//				SearchTagTotalPriceEnum.TOTAL_PRICE200PLUS.getName()));
//		tags.add(new BuildingTag(SearchTagTotalPriceEnum.TOTAL_PRICE300PLUS.getId(),Constants.TAG_TYPE_TOTAL_PRICE,
//				SearchTagTotalPriceEnum.TOTAL_PRICE300PLUS.getName()));
//		//第三排 自定义标签
//		tags.add(new BuildingTag(BuildingTagEnum.SCHOOL_HOUSE.getId(),Constants.TAG_TYPE_SYS,
//				BuildingTagEnum.SCHOOL_HOUSE.getName()));
//		tags.add(new BuildingTag(BuildingTagEnum.SUBWAY_ONE.getId(),Constants.TAG_TYPE_SYS,
//				BuildingTagEnum.SUBWAY_ONE.getName()));
//		tags.add(new BuildingTag(BuildingTagEnum.JIAN_DAO_CHA.getId(),Constants.TAG_TYPE_SYS,
//				BuildingTagEnum.JIAN_DAO_CHA.getName()));
//		tags.add(new BuildingTag(BuildingTagEnum.NOT_LIMIT_BUY.getId(),Constants.TAG_TYPE_SYS,
//				BuildingTagEnum.NOT_LIMIT_BUY.getName()));
//		m.put("home_tags", tags);
//		return ResultUtil.ok(m);
        return null;
    }

    public Object getTagConditions() {

        Map<String, Object> m = new HashMap<>();
        //处理区域
        List<BuildingTag> region = new ArrayList<>();
        for (SearchRegionEnum r : SearchRegionEnum.values()) {
            region.add(new BuildingTag(r.getId(), Constants.TAG_TYPE_REGION, r.getName()));
        }
        m.put("region", region);
        //处理总价
        List<BuildingTag> totalPrice = new ArrayList<>();
        for (SearchTagTotalPriceEnum tp : SearchTagTotalPriceEnum.values()) {
            totalPrice.add(new BuildingTag(tp.getId(), Constants.TAG_TYPE_TOTAL_PRICE, tp.getName()));
        }
        m.put("totalPrice", totalPrice);
        //处理单价
        List<BuildingTag> perPrice = new ArrayList<>();
        for (SearchPerPriceConditionEnum pp : SearchPerPriceConditionEnum.values()) {
            String name = "";
			/*
			 * 
	LESS_10000Y("10000元/㎡以内",1,0,10000),
	LESS_15000Y("10000-15000 元/㎡",2,10000,15000),
	LESS_20000Y("15000-20000 元/㎡",3,15000,20000),
	LESS_25000Y("20000-25000 元/㎡",4,20000,25000),
	LESS_30000Y("25000-30000 元/㎡",5,25000,30000),
	MORE_30000Y("30000 元/㎡以上",6,30000,1000000);
			 */
            if (pp.getId() == 1)
                name = "1 万以下";
            else if (pp.getId() == 2)
                name = "1-1.5 万";
            else if (pp.getId() == 3)
                name = "1.5-2 万";
            else if (pp.getId() == 4)
                name = "2-2.5 万";
            else if (pp.getId() == 5)
                name = "2.5-3 万";
            else if (pp.getId() == 6)
                name = "3 万以上";
            perPrice.add(new BuildingTag(pp.getId(), Constants.TAG_TYPE_PER_PRICE, name));
        }
        m.put("perPrice", perPrice);
        //处理面积
        List<BuildingTag> space = new ArrayList<>();
        for (SearchSpaceConditionEnum ss : SearchSpaceConditionEnum.values()) {
            space.add(new BuildingTag(ss.getId(), Constants.TAG_TYPE_SPACE, ss.getName()));
        }
        m.put("spcae", space);
        //处理户型
        List<BuildingTag> houseModel = new ArrayList<>();
        for (SearchHouseModelConditionEnum hm : SearchHouseModelConditionEnum.values()) {
            houseModel.add(new BuildingTag(hm.getId(), Constants.TAG_TYPE_HOUSE_MODEL, hm.getName()));
        }
        m.put("houseModel", houseModel);
        //处理地铁
        List<BuildingTag> subways = new ArrayList<>();
        for (SearchSubwayEnum sub : SearchSubwayEnum.values()) {
            subways.add(new BuildingTag(sub.getId(), Constants.TAG_TYPE_SUBWAY, sub.getName()));
        }
        m.put("subway", subways);
        //处理商场
        List<BuildingTag> market = new ArrayList<>();
        for (SearchTagMarketEnum tm : SearchTagMarketEnum.values()) {
            market.add(new BuildingTag(tm.getId(), Constants.TAG_TYPE_MARKET, tm.getName()));
        }
        m.put("market", market);
        //处理类别
        List<BuildingTag> types = new ArrayList<>();
        BuildingTagEnum[] bts = BuildingTagEnum.values();
        for (int i = 0; i < bts.length; i++) {
            if (i < 13)
                types.add(new BuildingTag(bts[i].getId(),
                        Constants.TAG_TYPE_SYS, bts[i].getName()));

        }
        m.put("types", types);
        //处理特色标签
        List<BuildingTag> other = new ArrayList<>();
        for (int i = 0; i < bts.length; i++) {
            if (i > 12)
                other.add(new BuildingTag(bts[i].getId(),
                        Constants.TAG_TYPE_SYS, bts[i].getName()));

        }
        m.put("feature", other);
        return ResultUtil.ok(m);
    }

    /**
     * 获取热搜的楼盘名字在搜索页面展示
     *
     * @return
     */
    public Object getHotSearchBuildingNames() {

        List<SimpleCoditionBean> hot = this.hpcs.getHotSearchListCache();
        if (hot == null) {
            //走数据库
            hot = this.hpm.getBuildingAdByType(Constants.AD_BUILDING_NAME_HOT_SEARCHS);
            this.hpcs.setHotSearchListCache(hot);
        }
        return ResultUtil.ok(getHotSearchMoreThan12(hot));
    }

    private List<SimpleCoditionBean> getHotSearchMoreThan12(List<SimpleCoditionBean> hot) {
        if (hot.size() <= 12)
            return hot;
        List<SimpleCoditionBean> res = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            res.add(hot.get(i));
        }
        res.add(hot.get(getRandom(12)));//随机选取12个展示
        return res;
    }


    private static int getRandom(int size) {
        //随机数 0到size-1
        int min = 0;
        int max = size;
        //返回值不包含bound参数值
        int r = new Random().nextInt(max - min) + min;
        return r;
    }

    /**
     * 获取搜索框占位的楼盘名字广告
     *
     * @return
     */
    public Object getSearchInputHoldpalce() {
        List<SimpleCoditionBean> inputs = this.hpcs.getInputHoldplaceNameCache();
        if (inputs == null) {
            inputs = this.hpm.getBuildingAdByType(Constants.AD_BUILDING_NANE_INPUTS_PLACEHOLDER);
            this.hpcs.setInputHoldplaceNameCache(inputs);
        }
        if (inputs.size() == 0) {
            Object x = "清秀未遮山";
            return ResultUtil.ok(x);
        }
        SimpleCoditionBean x = inputs.get(getRandom(inputs.size()));
        Object xn = x.getName();
        return ResultUtil.ok(xn);

    }

    //10000002  独家报道的栏目id
    public Object getDuJiaReport() {
        List<SimpleCoditionBean> dj = this.hpcs.getDuJiaReportCache();
        if (dj == null) {
            dj = this.hpm.getDuJiaReport(10000002);
            this.hpcs.setDuJiaReportCache(dj);
        }
        return ResultUtil.ok(dj);
    }

    /**
     * 获取首页推荐的楼盘信息
     *
     * @return
     */
    public Object getTuiJianLp() {

        Map<String, Object> m = new HashMap<>();
        //1、处理热门楼盘和即将取证的随机两个广告位数据
        handleRandomAd(m);
        //2、处理各类的置顶广告
        handleSetTops(m);
        //3、处理置顶数据不足的情况下各种类型随机展示数据
        handleRandomShowData(m);
        return ResultUtil.ok(m);
    }

    /**
     * 处理随机展示数据，最新取证和最新摇号按照时间排序取前三缓存，其他各缓存10条数据用于随机展示置顶之外的数据
     *
     * @param m
     */
    private void handleRandomShowData(Map<String, Object> m) {

        //先判断是否有缓存
        List<BuildingListDataBean> jjqzData = this.hpcs.getBuilding5TypeGeneralDataCache("jjqz");
        if (CollectionUtils.isEmpty(jjqzData)) {
            //缓存5种类型的数据到redis
            setJjqzDataCache();
            setZxqzDataCache();
            setZxyhDataCache();
            setYhsyDataCache();
            setRmlpDataCache();
        }
        //处理完后封装最后的数据====即将取证
        List<BuildingListDataBean> jjqzRes = (List<BuildingListDataBean>) m.get("jjqz");
        if (jjqzRes == null) {
            jjqzRes = new ArrayList<>(3);
            m.put("jjqz", jjqzRes);
        }
        getRandomListData(this.hpcs.getBuilding5TypeGeneralDataCache("jjqz"), 3 - jjqzRes.size(), jjqzRes);
        //热门楼盘
        List<BuildingListDataBean> rmlpRes = (List<BuildingListDataBean>) m.get("rmlp");
        if (rmlpRes == null) {
            rmlpRes = new ArrayList<>(3);
            m.put("rmlp", changeComments(rmlpRes));
        }
        getRandomListData(this.hpcs.getBuilding5TypeGeneralDataCache("rmlp"), 3 - rmlpRes.size(), rmlpRes);
        //摇号剩余
        List<BuildingListDataBean> yhsyRes = (List<BuildingListDataBean>) m.get("yhsy");
        if (yhsyRes == null) {
            yhsyRes = new ArrayList<>(3);
            m.put("yhsy", changeComments(yhsyRes));
        }
        getRandomListData(this.hpcs.getBuilding5TypeGeneralDataCache("yhsy"), 3 - yhsyRes.size(), yhsyRes);
        //最新取证
        List<BuildingListDataBean> zxqzRes = (List<BuildingListDataBean>) m.get("zxqz");
        if (zxqzRes == null) {
            zxqzRes = new ArrayList<>(3);
            m.put("zxqz", changeComments(zxqzRes));
        }
        getSortedListData(this.hpcs.getBuilding5TypeGeneralDataCache("zxqz"), 3 - zxqzRes.size(), zxqzRes);
        //最新摇号
        List<BuildingListDataBean> zxyhRes = (List<BuildingListDataBean>) m.get("zxyh");
        if (zxyhRes == null) {
            zxyhRes = new ArrayList<>(3);
            m.put("zxyh", changeComments(zxyhRes));
        }
        getSortedListData(this.hpcs.getBuilding5TypeGeneralDataCache("zxyh"), 3 - zxyhRes.size(), zxyhRes);
    }


    private void getSortedListData(List<BuildingListDataBean> meta, int returnNum, List<BuildingListDataBean> target) {
        if (returnNum == 0) {
            return;
        }
        for (int i = 0; i < meta.size(); i++) {
            BuildingListDataBean b = meta.get(i);
            if (!isRepeat(target, b)) {
                target.add(b);//不重复才加进去
            }
            if (target.size() >= 3) {
                return;
            }
        }
    }

    /**
     * @param meta      要被随机取出数据容器
     * @param returnNum 要取出的条数
     * @param target    取出后缓存的容器
     * @return
     */
    private void getRandomListData(List<BuildingListDataBean> meta, int returnNum, List<BuildingListDataBean> target) {
        if (returnNum == 0)
            return;
        int size = meta.size();
        for (int i = 0; i < returnNum && i < meta.size(); i++) {
            //不能重复
            int index = 0;
            while (index <= 200) {
                //死循环保护,极端情况下出现数据少等情况会死循环，这种情况最多执行20次
                index++;
                BuildingListDataBean radomData = meta.get(getRandom(size));
                boolean isRepeat = isRepeat(target, radomData);
                if (!isRepeat) {
                    target.add(radomData);
                    break;
                }
            }
        }
    }

    private boolean isRepeat(List<BuildingListDataBean> target, BuildingListDataBean d) {

        for (BuildingListDataBean t : target) {
            if (d.getId() == t.getId())
                return true;
        }
        return false;
    }


    private void setJjqzDataCache() {

        //从es查询10条随机数据缓存
//        QueryBuilder query = QueryBuilders.termQuery("sellStatus", SellStateEnum.PRE_SELL.getId());
        QueryBuilder query = QueryBuilders.wildcardQuery("type", "*" + BuildingGroupEnum.notCertification.getCode() + "*");
        Script sc = new Script("Math.random()");
        SortBuilder sort = SortBuilders.scriptSort(sc, ScriptSortType.NUMBER);
        List<SortBuilder> sorts = new ArrayList<>();
        sorts.add(sort);
        //执行查询,随机十条
        List<Map<String, Object>> res = doSearchFromEs(query, sorts, 1,
                10, BuildingSearchService.getFileds(false));
        //结果处理
        List<BuildingSearchDocumentBean> rex = new ArrayList<>();
        res.forEach(d -> {
            //将map转换为对象进行数据处理
            rex.add(JSON.parseObject(JSON.toJSONString(d), BuildingSearchDocumentBean.class));
        });
        //处理数据并封装返回
        List<BuildingListDataBean> data = BuildingSearchService.handleResultData(rex);
        this.hpcs.setBuilding5TypeGeneralDataCache(Constants.HOME_PAGE_BUILDING_TYPE_JJQZ, data);
    }

    /**
     * 最新取证查询三条。按照预售时间降序排列
     */
    private void setZxqzDataCache() {

        BoolQueryBuilder zxqz = QueryBuilders.boolQuery();
        //分类匹配
        zxqz.must(QueryBuilders.wildcardQuery("type", "*" + BuildingGroupEnum.newCertification.getCode().toLowerCase() + "*"));
        //小于开始公示时间
        SimpleDateFormat sdfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
        long now = 0l;
        try {
            now = sdfs.parse(sdf.format(new Date())).getTime();
        } catch (ParseException e) {
        }
        List<SortBuilder> sorts = new ArrayList<>();
        //排序过滤条件是开盘的数据里，必须满足当前时间小于摇号时间
        NestedSortBuilder ns = new NestedSortBuilder("kps");
        BoolQueryBuilder kpsort = QueryBuilders.boolQuery();
        kpsort.must(QueryBuilders.rangeQuery("kps.yaohao").gte(now));
        kpsort.must(QueryBuilders.rangeQuery("kps.preSellTime").lte(now));
        ns.setFilter(kpsort);
        SortBuilder sort = SortBuilders.fieldSort("kps.preSellTime").setNestedSort(ns).order(SortOrder.DESC);
        sorts.add(sort);
        //执行查询
        List<Map<String, Object>> res = doSearchFromEs(zxqz, sorts, 1,
                3, BuildingSearchService.getFileds(false));
        //结果处理
        List<BuildingSearchDocumentBean> rex = new ArrayList<>();
        res.forEach(d -> {
            //将map转换为对象进行数据处理
            rex.add(JSON.parseObject(JSON.toJSONString(d), BuildingSearchDocumentBean.class));
        });
        //处理数据并封装返回
        List<BuildingListDataBean> data = BuildingSearchService.handleResultData(rex);
        this.hpcs.setBuilding5TypeGeneralDataCache(Constants.HOME_PAGE_BUILDING_TYPE_ZXQZ, data);
    }

    /**
     * 最新摇号，按照摇号时间查询最近3条且还要处理摇号数据
     */
    private void setZxyhDataCache() {

        BoolQueryBuilder zxyh = QueryBuilders.boolQuery();
        //678都是,使用或者
        zxyh.must(QueryBuilders.wildcardQuery("type", "*" + BuildingGroupEnum.newShakeNumber.getCode() + "*"));
        BoolQueryBuilder zxyhT5NestBool = QueryBuilders.boolQuery();
        //大于开始公示时间
        SimpleDateFormat sdfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
        long now = 0l;
        try {
            now = sdfs.parse(sdf.format(new Date())).getTime();
        } catch (ParseException e) {
        }
        QueryBuilder range = QueryBuilders.rangeQuery("kps.startPublify").lte(now);
        zxyhT5NestBool.must(range);
        //且要满足当前时间-5天小于选房结束时间
        Calendar cl = Calendar.getInstance();
        cl.setTime(new Date());
        cl.add(Calendar.DATE, -5);
        long ct = 0l;
        try {
            ct = sdfs.parse(sdf.format(cl.getTime())).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        QueryBuilder limitSelect = QueryBuilders.rangeQuery("kps.endSelect").gte(ct);
        zxyhT5NestBool.must(limitSelect);
        List<SortBuilder> sorts = new ArrayList<>();
        //排序过滤条件是开盘的数据里，必须满足当前时间-5天小于选房结束时间
        NestedSortBuilder ns = new NestedSortBuilder("kps");
        BoolQueryBuilder kpsort = QueryBuilders.boolQuery();
        kpsort.must(QueryBuilders.rangeQuery("kps.endSelect").gte(now));
        kpsort.must(QueryBuilders.rangeQuery("kps.preSellTime").lte(now));
        ns.setFilter(kpsort);
        SortBuilder sort = SortBuilders.fieldSort("kps.yaohao").setNestedSort(ns).order(SortOrder.DESC);
        sorts.add(sort);

        //执行查询
        List<Map<String, Object>> res = doSearchFromEs(zxyh, sorts, 1,
                3, BuildingSearchService.getFileds(false));
        //结果处理
        List<BuildingSearchDocumentBean> rex = new ArrayList<>();
        res.forEach(d -> {
            //将map转换为对象进行数据处理
            rex.add(JSON.parseObject(JSON.toJSONString(d), BuildingSearchDocumentBean.class));
        });
        //处理数据并封装返回
        List<BuildingListDataBean> data = BuildingSearchService.handleResultData(rex);
        //还要处理摇号数据
        handleYaoHaoData(data);
        this.hpcs.setBuilding5TypeGeneralDataCache(Constants.HOME_PAGE_BUILDING_TYPE_ZXYH, data);
    }

    /**
     * 按照摇号时间降序排列
     */
    private void setYhsyDataCache() {

        BoolQueryBuilder meta = QueryBuilders.boolQuery();
        QueryBuilder query = QueryBuilders.rangeQuery("suplusHose").gte(20);
        meta.must(query);
        meta.must(QueryBuilders.wildcardQuery("type", "*" + BuildingGroupEnum.bestSellerBuild.getCode() + "*"));
        Script sc = new Script("Math.random()");
        SortBuilder sort = SortBuilders.scriptSort(sc, ScriptSortType.NUMBER);
        List<SortBuilder> sorts = new ArrayList<>();
        sorts.add(sort);
        //执行查询,随机十条
        List<Map<String, Object>> res = doSearchFromEs(meta, sorts, 1,
                10, BuildingSearchService.getFileds(false));
        //结果处理
        List<BuildingSearchDocumentBean> rex = new ArrayList<>();
        res.forEach(d -> {
            //将map转换为对象进行数据处理
            rex.add(JSON.parseObject(JSON.toJSONString(d), BuildingSearchDocumentBean.class));
        });
        //处理数据并封装返回
        List<BuildingListDataBean> data = BuildingSearchService.handleResultData(rex);
        this.hpcs.setBuilding5TypeGeneralDataCache(Constants.HOME_PAGE_BUILDING_TYPE_YHSY, data);
    }

    private void setRmlpDataCache() {

        //从es查询10条随机数据缓存
        QueryBuilder query = QueryBuilders.wildcardQuery("type", "*" + BuildingGroupEnum.hotBuild.getCode() + "*");
        Script sc = new Script("Math.random()");
        SortBuilder sort = SortBuilders.scriptSort(sc, ScriptSortType.NUMBER);
        List<SortBuilder> sorts = new ArrayList<>();
        sorts.add(sort);
        //执行查询,随机十条
        List<Map<String, Object>> res = doSearchFromEs(query, sorts, 1,
                10, BuildingSearchService.getFileds(false));
        //结果处理
        List<BuildingSearchDocumentBean> rex = new ArrayList<>();
        res.forEach(d -> {
            //将map转换为对象进行数据处理
            rex.add(JSON.parseObject(JSON.toJSONString(d), BuildingSearchDocumentBean.class));
        });
        //处理数据并封装返回
        List<BuildingListDataBean> data = BuildingSearchService.handleResultData(rex);
        this.hpcs.setBuilding5TypeGeneralDataCache(Constants.HOME_PAGE_BUILDING_TYPE_RMLP, data);
    }


    //处理置顶
    private void handleSetTops(Map<String, Object> m) {

        List<BuildingListDataBean> jjqzTop = this.hpcs.getBuildingTops("jjqz");
        if (CollectionUtils.isEmpty(jjqzTop)) {
            //缓存所有的置顶数据到redis
            List<HomePageAdBean> tops = this.hpm.getHomePageAllTops();
            if (tops.size() > 15) {
                log.info("置顶的数据总条数大于15条，错误，不处理置顶数据");
                return;
            }
            setTops2Redis(tops, m);
            if (tops.size() == 0) {
                return;
            }
        }
        //不为空的情况下直接查询对应类型的置顶数据进行返回
        m.put(Constants.HOME_PAGE_BUILDING_TYPE_RMLP, changeComments(this.hpcs.getBuildingTops("rmlp")));
        m.put(Constants.HOME_PAGE_BUILDING_TYPE_JJQZ, changeComments(jjqzTop));
        m.put(Constants.HOME_PAGE_BUILDING_TYPE_ZXQZ, changeComments(this.hpcs.getBuildingTops("zxqz")));
        m.put(Constants.HOME_PAGE_BUILDING_TYPE_ZXYH, changeComments(this.hpcs.getBuildingTops("zxyh")));
        m.put(Constants.HOME_PAGE_BUILDING_TYPE_YHSY, changeComments(this.hpcs.getBuildingTops("yhsy")));
    }

    /**
     * 处理评论数量与详情页不统一
     *
     * @param beans
     * @return
     */
    private List<BuildingListDataBean> changeComments(List<BuildingListDataBean> beans) {
        beans.parallelStream().forEach(bean -> bean.setComments(String.valueOf(Integer.valueOf(bean.getComments()) + 1)));
        return beans;
    }

    private void setTops2Redis(List<HomePageAdBean> tops, Map<String, Object> m) {
        List<BuildingListDataBean> rmlp = new ArrayList<>();
        List<BuildingListDataBean> jjqz = new ArrayList<>();
        List<BuildingListDataBean> zxqz = new ArrayList<>();
        List<BuildingListDataBean> zxyh = new ArrayList<>();
        List<BuildingListDataBean> yhsy = new ArrayList<>();
        if (tops.size() == 0) {
            hpcs.setBuildingTops(Constants.HOME_PAGE_BUILDING_TYPE_RMLP, rmlp);
            hpcs.setBuildingTops(Constants.HOME_PAGE_BUILDING_TYPE_JJQZ, jjqz);
            hpcs.setBuildingTops(Constants.HOME_PAGE_BUILDING_TYPE_ZXQZ, zxqz);
            hpcs.setBuildingTops(Constants.HOME_PAGE_BUILDING_TYPE_ZXYH, zxyh);
            hpcs.setBuildingTops(Constants.HOME_PAGE_BUILDING_TYPE_YHSY, yhsy);
            return;
        }
        int bids[] = new int[tops.size()];
        for (int i = 0; i < tops.size(); i++) {
            bids[i] = tops.get(i).getBuildingId();
        }
        //去es查询出结构化后的数据
        List<BuildingListDataBean> datas = this.getDataFromEs(bids);
        //按类型处理数据分类,外层的顺序排
        for (HomePageAdBean ad : tops) {
            for (BuildingListDataBean data : datas) {
                if (data.getId() == ad.getBuildingId()) {
                    switch (ad.getTopType()) {
                        case Constants.HOME_PAGE_BUILDING_TYPE_RMLP:
                            rmlp.add(data);
                            break;
                        case Constants.HOME_PAGE_BUILDING_TYPE_JJQZ:
                            jjqz.add(data);
                            break;
                        case Constants.HOME_PAGE_BUILDING_TYPE_ZXQZ:
                            zxqz.add(data);
                            break;
                        case Constants.HOME_PAGE_BUILDING_TYPE_ZXYH:
                            zxyh.add(data);
                            break;
                        case Constants.HOME_PAGE_BUILDING_TYPE_YHSY:
                            yhsy.add(data);
                            break;
                    }
                }
            }
        }
        //最新摇号单独查询 开盘信息计算摇号概率等数据
        if (zxyh.size() > 0) {
            //单独处理摇号信息等计算
            handleYaoHaoData(zxyh);
        }
        //设置到redis缓存
        hpcs.setBuildingTops(Constants.HOME_PAGE_BUILDING_TYPE_RMLP, rmlp);
        hpcs.setBuildingTops(Constants.HOME_PAGE_BUILDING_TYPE_JJQZ, jjqz);
        hpcs.setBuildingTops(Constants.HOME_PAGE_BUILDING_TYPE_ZXQZ, zxqz);
        hpcs.setBuildingTops(Constants.HOME_PAGE_BUILDING_TYPE_ZXYH, zxyh);
        hpcs.setBuildingTops(Constants.HOME_PAGE_BUILDING_TYPE_YHSY, yhsy);
        //把各类的置顶数据存入要返回的数据里
        m.put(Constants.HOME_PAGE_BUILDING_TYPE_RMLP, rmlp);
        m.put(Constants.HOME_PAGE_BUILDING_TYPE_JJQZ, jjqz);
        m.put(Constants.HOME_PAGE_BUILDING_TYPE_ZXQZ, zxqz);
        m.put(Constants.HOME_PAGE_BUILDING_TYPE_ZXYH, zxyh);
        m.put(Constants.HOME_PAGE_BUILDING_TYPE_YHSY, yhsy);
    }


    private void handleYaoHaoData(List<BuildingListDataBean> buildings) {
        List<OpenInfoBean> ops = this.hpm.getOpenInfoByBuildingId(buildings);
        if (ops.size() == 0)
            return;
        DecimalFormat df = new DecimalFormat(".##");
        for (OpenInfoBean o : ops) {
            if (o.getGxHouseNum() == null)
                o.setGxHouseNum(0);
            if (o.getPgHoseNum() == null)
                o.setPgHoseNum(0);
            if (o.getPtHouseNum() == null)
                o.setPtHouseNum(0);
            int allHose = o.getGxHouseNum() + o.getPtHouseNum() + o.getPgHoseNum();
            if (allHose == 0)
                continue;
            //棚改
            if (o.getPgHoseNum() == null || o.getPgHoseNum() == 0) {
                o.setPgRate("-");
                o.setPgHoseNum(0);
                o.setPgyhNum(0);
            } else if (o.getPgyhNum() == null || o.getPgyhNum() == 0) {
                o.setPgRate("-");
                o.setPgyhNum(0);
            } else {
                float r = Float.valueOf(o.getPgHoseNum()) / Float.valueOf(o.getPgyhNum());
                o.setPgRate(df.format(r * 100f) + "%");
            }
            //刚需
            if (o.getGxHouseNum() == null || o.getGxHouseNum() == 0) {
                o.setGxRate("-");
                o.setGxHouseNum(0);
                o.setGxyhNum(0);
            } else if (o.getGxyhNum() == null || o.getGxyhNum() == 0) {
                o.setGxRate("-");
                o.setGxyhNum(0);
            } else {
                float r = Float.valueOf(o.getGxHouseNum()) / Float.valueOf(o.getGxyhNum());
                o.setGxRate(df.format(r * 100f) + "%");
            }
            //普通  pt房源+（pg房源-pg报名）+（gx房源-刚需报名）/普通报名
            int ptall = 0;
            if (o.getPgHoseNum() > o.getPgyhNum())
                ptall += o.getPgHoseNum() - o.getPgyhNum();
            if (o.getGxHouseNum() > o.getGxyhNum())
                ptall += o.getGxHouseNum() - o.getGxyhNum();
            if (o.getPtHouseNum() != null)
                ptall += o.getPtHouseNum();
            if (o.getPtHouseNum() == null || o.getPtHouseNum() == 0) {
                o.setPtRate("-");
                o.setPtHouseNum(0);
                o.setPtyhNum(0);
            } else if (o.getPtyhNum() == null || o.getPtyhNum() == 0) {
                o.setPtRate("-");
                o.setPtyhNum(0);
            } else {
                float r = Float.valueOf(ptall) / Float.valueOf(o.getPtyhNum());
                o.setPtRate(df.format(r * 100f) + "%");
            }
            KaiPanData kp = new KaiPanData();
            kp.setTotalHouse(allHose);
            kp.setGxRate(o.getGxRate());
            kp.setPgRate(o.getPgRate());
            kp.setPtRage(o.getPtRate());
            //设置到对应的数据里
            for (BuildingListDataBean b : buildings) {
                if (b.getId() == o.getBuildingId().intValue()) {
                    b.setKaiPanInfo(kp);
                    break;
                }
            }
        }
    }


    //处理随机广告
    private void handleRandomAd(Map<String, Object> m) {
        //先看看有没有热门楼盘的广告位数据
        List<BuildingListDataBean> hotAd = this.hpcs.getBuildingAd_RmlpOrJjqzCache("rmlp");
        if (hotAd == null) {
            log.info("没有缓存的广告,拉取数据库数据并从es查询出具体数据");
            //走数据库查询这两类广告的类型和id
            List<HomePageAdBean> ads = this.hpm.getHomePageBuildingAds();
            if (ads.size() == 0) {
                //把空的数据放进去 避免缓存穿透
                hpcs.setBuildingAd_RmlpOrJjqz(Constants.HOME_PAGE_BUILDING_TYPE_RMLP, new ArrayList<BuildingListDataBean>(0));
                hpcs.setBuildingAd_RmlpOrJjqz(Constants.HOME_PAGE_BUILDING_TYPE_JJQZ, new ArrayList<BuildingListDataBean>(0));
                log.info("没有缓存的广告,存入redis空数据避免缓存穿透");
                m.put("housead_rmlp", null);
                m.put("housead_jjqz", null);
                return;
            }
            int[] bids = new int[ads.size()];
            for (int i = 0; i < ads.size(); i++) {
                bids[i] = ads.get(i).getBuildingId();
            }
            //去es查询出结构化后的数据
            List<BuildingListDataBean> datas = this.getDataFromEs(bids);
            //根据类型分别存入redis
            setAds2Redis(datas, ads);
        }
        //缓存后从新从缓存内拉出各类的广告随机取一个
        hotAd = this.hpcs.getBuildingAd_RmlpOrJjqzCache(Constants.HOME_PAGE_BUILDING_TYPE_RMLP);
        BuildingListDataBean hot = null;
        if (hotAd.size() > 0) {
            hot = hotAd.get(getRandom(hotAd.size()));
        }
        List<BuildingListDataBean> jjqzs = this.hpcs.getBuildingAd_RmlpOrJjqzCache("jjqz");
        BuildingListDataBean jjqz = null;
        if (jjqzs.size() > 0) {
            jjqz = jjqzs.get(getRandom(jjqzs.size()));
        }
        log.info("首页楼盘广告数量:rmlp" + hotAd.size() + ",jjqz:" + jjqzs.size());
        hot.setComments(String.valueOf(Integer.parseInt(hot.getComments()) + 1));
        m.put("housead_rmlp", hot);
        hot.setComments(String.valueOf(Integer.parseInt(jjqz.getComments()) + 1));
        m.put("housead_jjqz", jjqz);
    }

    private void setAds2Redis(List<BuildingListDataBean> datas, List<HomePageAdBean> ads) {

        List<BuildingListDataBean> rmlp = new ArrayList<>();
        List<BuildingListDataBean> jjqz = new ArrayList<>();
        for (BuildingListDataBean data : datas) {
            for (HomePageAdBean ad : ads) {
                if (data.getId() == ad.getBuildingId()) {
                    if (ad.getAdType().equals(Constants.HOME_PAGE_BUILDING_TYPE_RMLP)) {
                        rmlp.add(data);
                    } else {
                        jjqz.add(data);
                    }
                }
            }
        }
        this.hpcs.setBuildingAd_RmlpOrJjqz(Constants.HOME_PAGE_BUILDING_TYPE_RMLP, rmlp);
        this.hpcs.setBuildingAd_RmlpOrJjqz(Constants.HOME_PAGE_BUILDING_TYPE_JJQZ, jjqz);
    }

    private List<BuildingListDataBean> getDataFromEs(int[] bids) {

        QueryBuilder query = QueryBuilders.termsQuery("id", bids);
        //执行查询
        List<Map<String, Object>> res = doSearchFromEs(query, null, -1,
                0, BuildingSearchService.getFileds(false));
        //结果处理
        List<BuildingSearchDocumentBean> rex = new ArrayList<>();
        res.forEach(d -> {
            //将map转换为对象进行数据处理
            rex.add(JSON.parseObject(JSON.toJSONString(d), BuildingSearchDocumentBean.class));
        });
        //处理数据并封装返回
        List<BuildingListDataBean> data = BuildingSearchService.handleResultData(rex);
        return data;
    }

    @SuppressWarnings("rawtypes")
    private List<Map<String, Object>> doSearchFromEs(QueryBuilder query, List<SortBuilder> sorts,
                                                     int page, int size, String[] fields) {
        SearchRequestBuilder req = esTemplate.getClient().prepareSearch(Constants.ES_BUILDING_INDEX_NAME)
                .setTypes(Constants.ES_TYPE_NAME_HOUSE);
        req.setQuery(query);
        //设置分页
        if (page > 0) {
            req.setFrom((page - 1) * size).setBatchedReduceSize(size);
        }
        //设置排序,多个排序体
        if (sorts != null) {
            sorts.forEach(s -> req.addSort(s));
        }
        //设置返回的置顶字段
        req.setFetchSource(fields, null);
        //执行查询
        SearchResponse rep = req.execute().actionGet();
        List<Map<String, Object>> all = new ArrayList<Map<String, Object>>();
        rep.getHits().forEach(h -> {
            Map<String, Object> res = h.getSourceAsMap();
            all.add(res);
        });
        return all;
    }


    // 获取房产新闻数据列表
    public Object getFangChanNewList(Integer page) {
        if (page == null || page <= 1) {
            page = 0;
        } else {
            page = (page - 1) * 20;
        }
        Map<String, Object> m = new HashMap<>();
        m.put("total", hpm.getTotal());
        m.put("newList", hpm.getFangChanNewList(page));
        return ResultUtil.ok(m);
    }

    // 独家报道
    public Object getDuJiaReportV2_2() {
        List<SimpleCoditionBean> dj = this.hpcs.getDuJiaReportV2_2();
        if (dj == null) {
            dj = this.hpm.getDuJiaReportV2_2(2);
            this.hpcs.setDuJiaReportV2_2(dj);
        }
        return ResultUtil.ok(dj);
    }


    public Object getZaoBaoList(Integer page) {
        if (page == null || page < 1)
            page = 1;
        Map<String, Object> m = new HashMap<>();
        m.put("page", (page - 1) * 15);
        m.put("size", 15);
        Integer total = this.hpm.getZaoBaoListTotal(m);
        if (total == null || total == 0) {
            m.clear();
            m.put("total", 0);
            m.put("rows", new ArrayList<>());
            return ResultUtil.ok(m);
        }
        List<ZaoBaoBean> ls = this.hpm.getZaoBaoList(m);
        //处理数据
        ls.forEach(z -> handleZaoBaoTime(z));
        m.clear();
        m.put("total", total);
        m.put("rows", ls);
        return ResultUtil.ok(m);
    }

    private void handleZaoBaoTime(ZaoBaoBean zbb) {

        //处理时间
        Date time = zbb.getCreateTime();
        Calendar cl = Calendar.getInstance();
        cl.setTime(time);
        int x = cl.get(Calendar.DAY_OF_WEEK);//1是星期天
        String xq = "";
        switch (x) {
            case 1:
                xq = "星期天";
                break;
            case 2:
                xq = "星期一";
                break;
            case 3:
                xq = "星期二";
                break;
            case 4:
                xq = "星期三";
                break;
            case 5:
                xq = "星期四";
                break;
            case 6:
                xq = "星期五";
                break;
            case 7:
                xq = "星期六";
                break;
        }
        zbb.setXingQi(xq);
    }


    public Object getZaoBaoDetail(Integer id) {
        String ed = null;
        if (id == null || id < 1) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            ed = sdf.format(new Date()) + " 23:59:59";
        }
        ZaoBaoBean zbb = this.hpm.getZaoBaoDetail(id, ed);
        if (zbb == null)
            return ResultUtil.ok(null);
        //处理时间
        this.handleZaoBaoTime(zbb);
        //处理楼盘信息
        zbb.setRegs(handleBuildingInfo(zbb.getReg()));
        zbb.setYhs(handleBuildingInfo(zbb.getYh()));
        zbb.setReg(null);
        zbb.setYh(null);
        return ResultUtil.ok(zbb);
    }


    private List<ZaoBaoBuildingInfo> handleBuildingInfo(String jsonData) {
        if (StringUtils.isEmpty(jsonData))
            return null;
        return JSON.parseArray(jsonData, ZaoBaoBuildingInfo.class);
    }


    public Object getZaoBaoPost(Integer zaoBaoId, int customerId) {

        if (zaoBaoId == null)
            return ResultUtil.fail("生成海报失败");

        //准备早报数据
        ZaoBaoBean zbb = this.getZaoBaoData(zaoBaoId);
        if (zbb == null)
            return ResultUtil.fail("生成海报失败");
        //准备用户数据
        boolean isSellMan = this.isSellMan(customerId);
        //准备二维码
        byte[] qrCode = null;
        //本地二维码测试
        try {
            qrCode = this.getZaobaoQRCode(zaoBaoId, isSellMan ? customerId : null);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ResultUtil.fail("生成海报失败");
        }
//		FileInputStream fis= null;
//		try {
//			fis = new FileInputStream(new File("D:\\text\\qr.png"));
//		} catch (Exception e1) {
//		}
//		try {
//			qrCode = new byte[fis.available()];
//			fis.read(qrCode);
//		} catch (Exception e1) {
//		}finally {
//			try {
//				fis.close();
//			} catch (IOException e) {
//			}
//		}
        if (qrCode == null || qrCode.length == 0) {
            log.error("获取小程序二维码失败");
            return ResultUtil.fail("生成海报失败");
        }
        //进行合成
        try {
            byte[] img = autoCreatePost(qrCode, zbb);
            if (img == null || img.length == 0)
                return ResultUtil.fail("生成海报失败");
            String imgStr = Base64.getEncoder().encodeToString(img);
            return ResultUtil.ok(null, imgStr);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ResultUtil.fail("生成海报失败");
        }
    }


    private byte[] autoCreatePost(byte[] qrCode, ZaoBaoBean zbb) throws Exception {

        //750，1550
        int x = 750;
        int y = 1550;
        //创建底板画布
        BufferedImage billImgBuffer = new BufferedImage(x, y, BufferedImage.TYPE_INT_RGB);// RGB形式
        Graphics2D bill2d = billImgBuffer.createGraphics();
        bill2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);//抗锯齿
        bill2d.setBackground(Color.WHITE);//设置背景为白色
        bill2d.clearRect(0, 0, 800, 1600);//通过使用当前绘图表面的背景色进行填充来清除指定的矩形
        //绘制背景图
        drawBackGroundImg(bill2d, x, y);
        //绘制时间
        drawTime(bill2d, zbb);
        //绘制内容
        drawContent(bill2d, zbb);
        //绘制二维码
        drawQrCode(bill2d, qrCode);
        //结束绘制,转成byte[]数组
        bill2d.dispose();
        FileOutputStream fos = new FileOutputStream(new File("D:\\text\\zbb.png"));
        ImageIO.write(billImgBuffer, "png", fos);
        fos.close();
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ImageIO.write(billImgBuffer, "png", byteOut);
        byte[] b = byteOut.toByteArray();
        return b;
    }

    private void drawContent(Graphics2D bill2d, ZaoBaoBean zbb) throws Exception {

        //绘制dj
        int y = drawDjlp(bill2d, zbb.getRegs());
        if (y > 1362) return;
        //绘制摇号
        y = drawYhlp(bill2d, zbb.getYhs(), y);
        if (y > 1362) return;
        //绘制咨询内容
        y = drawZx(bill2d, zbb.getContent(), y);
        if (y > 1362) return;

    }


    private int drawZx(Graphics2D bill2d, String content, int y) throws Exception {

        y = y + 41;
        bill2d.drawImage(ImageIO.read(new URL(this.xwUrl)), 255, y, null);
        y = y + 56 + 50;
        //咨询内容是富文本，将富文本转换为字符串、
        HtmlToText h = new HtmlToText();//将富文本转为纯文本
        h.parse(content);
        List<String> sections = h.getString();//段落的数据，需要切分
        List<String> zxs = splitZx(sections);
        Color cc = new Color(54, 54, 54);
        bill2d.setPaint(cc);// 设置画笔,设置Paint属性
        Font font = new Font("黑体", Font.PLAIN, 24);
        bill2d.setFont(font);
        int height = 20;
        for (int i = 0; i < zxs.size(); i++) {
            String s = zxs.get(i);
            int nowy = y + i * (height + 24);
            int nextY = y + (i + 1) * (height + 24);
            if (nextY >= 1362 && (i + 1) < zxs.size())
                s = getLastLine(s);
            if (nowy > 1362) return nowy;
            bill2d.drawString(s, 64, nowy);
        }
        return y + ((zxs.size() - 1) * height);
    }

    private String getLastLine(String x) {
        return x.substring(0, x.length() - 3) + "...";
    }


    /**
     * 将回到的内容、段落切分
     */
    private List<String> splitZx(List<String> sections) {
        List<String> lines = new ArrayList<>();
        float words = 0f;
        StringBuilder sb = new StringBuilder();
        for (String section : sections) {
            char[] cs = section.toCharArray();
            for (int i = 0; i < cs.length; i++) {
                sb.append(cs[i]);
                words += (isEnglish(cs[i]) ? 0.5f : 1f);
                float nextLineWrods = i < cs.length - 1 ? nextLineCount(words, cs[i + 1]) : words;
                if (i == cs.length - 1 || nextLineWrods > 26) {
                    lines.add(sb.toString());
                    words = 0f;
                    sb = new StringBuilder();
                }
            }
        }
        return lines;
    }


    private boolean isEnglish(char c) {
        return (c >= 0 && c <= 127);
    }

    private float nextLineCount(float lineCount, char c) {
        return lineCount += (isEnglish(c) ? 0.55f : 1f);
    }


    private int drawYhlp(Graphics2D bill2d, List<ZaoBaoBuildingInfo> yhs, int y) throws Exception {
        y = y + 40;
        bill2d.drawImage(ImageIO.read(new URL(this.yhUrl)), 235, y, null);
        y = y + 56 + 50;
        if (yhs == null || yhs.size() == 0) {
            //今日暂无可登记楼盘
            Color cc = new Color(130, 130, 130);
            bill2d.setPaint(cc);// 设置画笔,设置Paint属性
            bill2d.drawString("今日无可摇号楼盘", 280, y);
            return y;
        } else {
            int height = 33;
            for (int i = 0; i < yhs.size(); i++) {
                ZaoBaoBuildingInfo zbb = yhs.get(i);
                Color cc = new Color(54, 54, 54);
                bill2d.setPaint(cc);// 设置画笔,设置Paint属性
                Font font = new Font("黑体", Font.PLAIN, 24);
                bill2d.setFont(font);
                int nowy = y + (height + 24) * i;
                if (nowy > 1362) return 1362;
                bill2d.drawString(zbb.getAreaName(), 64, nowy);
                Color cb = new Color(98, 129, 193);
                bill2d.setPaint(cb);// 设置画笔,设置Paint属性
                bill2d.drawString(zbb.getBuildingName(), 248, nowy);
                bill2d.setPaint(cc);
                bill2d.drawString("(" + zbb.getYHTime() + ")", 526, nowy);
            }
            return y + (height + 24) * (yhs.size() - 1);
        }
    }


    private int drawDjlp(Graphics2D bill2d, List<ZaoBaoBuildingInfo> djs) throws Exception {
        //绘制dj logo
        bill2d.drawImage(ImageIO.read(new URL(this.djUrl)), 235, 423, null);
        //绘制登记文字
        if (djs == null || djs.size() == 0) {
            //今日暂无可登记楼盘
            Color cc = new Color(130, 130, 130);
            bill2d.setPaint(cc);// 设置画笔,设置Paint属性
            Font font = new Font("黑体", Font.PLAIN, 24);//平方加粗30字号
            bill2d.setFont(font);
            bill2d.drawString("今日无可登记楼盘", 280, 520);
            return 520 + 24;
        } else {
            int y = 520;
            int height = 33;
            for (int i = 0; i < djs.size(); i++) {
                ZaoBaoBuildingInfo zbb = djs.get(i);
                Color cc = new Color(54, 54, 54);
                bill2d.setPaint(cc);// 设置画笔,设置Paint属性
                Font font = new Font("黑体", Font.PLAIN, 24);
                bill2d.setFont(font);
                int nowy = y + (height + 24) * i;
                if (nowy > 1362) return 1362;
                bill2d.drawString(zbb.getAreaName(), 64, nowy);
                Color cb = new Color(98, 129, 193);
                bill2d.setPaint(cb);// 设置画笔,设置Paint属性
                bill2d.drawString(zbb.getBuildingName(), 248, nowy);
                bill2d.setPaint(cc);
                bill2d.drawString("(" + zbb.getRegTime() + ")", 526, nowy);
            }
            return y + (height + 24) * (djs.size() - 1);
        }
    }


    private void drawQrCode(Graphics2D bill2d, byte[] qrCode) throws Exception {
        //创建二维码的指定大小画布
        BufferedImage qrCodeImg = new BufferedImage(130, 130, BufferedImage.TYPE_INT_RGB);
        Graphics2D qr2d = qrCodeImg.createGraphics();
        ByteArrayInputStream bin = new ByteArrayInputStream(qrCode);
        //将二维码图片绘制在画布上,按照画布进行缩放
        qr2d.drawImage(ImageIO.read(bin), 0, 0, 130, 130, null);
        qr2d.dispose();
        //将二维码绘制到背景图上下文
        bill2d.drawImage(qrCodeImg, 168, 1393, 130, 130, null);
    }


    private void drawTime(Graphics2D bill2d, ZaoBaoBean zbb) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(zbb.getCreateTime());
        Color cc = new Color(255, 255, 255);
        bill2d.setPaint(cc);// 设置画笔,设置Paint属性
        Font font = new Font("黑体", Font.PLAIN, 30);//平方加粗30字号
        bill2d.setFont(font);//设置画笔

        bill2d.drawString(date, 300, 327);
    }

    private void drawBackGroundImg(Graphics2D bill2d, int x, int y) throws Exception {
        BufferedImage bgImg = ImageIO.read(new URL(zaobaoBackUrl));
        bill2d.drawImage(bgImg, 0, 0, x, y, null);
    }

    private byte[] getZaobaoQRCode(int zid, Integer sellManId) throws Exception {
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit"
                + "?access_token=" + this.wxAcctkCacheService.getMiniprogramAcctk();
        Map<String, String> m = new HashMap<>();
        m.put("page", "pages/house/newsletter/index/main");
        String param = "zid=" + zid + (sellManId == null ? "" : "&sid=" + sellManId);
        m.put("scene", param);
        HttpHeaders headers = new HttpHeaders();
        //设置请求媒体数据类型
        headers.setContentType(MediaType.APPLICATION_JSON);
        String json = JSON.toJSONString(m);
        HttpEntity<String> formEntity = new HttpEntity<String>(json, headers);
        ResponseEntity<byte[]> res = restTemplate.postForEntity(url, formEntity, byte[].class);
        byte[] x = res.getBody();
        return x;
    }


    private ZaoBaoBean getZaoBaoData(int id) {
        ZaoBaoBean zbb = this.hpm.getZaoBaoDetail(id, null);
        if (zbb == null)
            return null;
        zbb.setRegs(handleBuildingInfo(zbb.getReg()));
        zbb.setYhs(handleBuildingInfo(zbb.getYh()));
        zbb.setReg(null);
        zbb.setYh(null);
        return zbb;
    }

    /**
     * 该用户是否可以在该楼盘下评论
     */
    public boolean isSellMan(int cid) {
        String url = customerServiceUrl + "/getSellManInfo?sellManCustomerId=" + cid;
        String res = ribonTemplate.getForObject(url, String.class);
        log.info("服务内部调用置业顾问信息接口:" + res);
        JSONObject result = JSON.parseObject(res);
        int code = result.getIntValue("code");
        if (code != 200)
            return false;
        JSONObject data = result.getJSONObject("data");
        if (data == null)
            return false;
        Integer sellManBuildingId = data.getInteger("buildingId");
        if (sellManBuildingId == null)
            return false;
        return true;
    }
}
